package com.jic.weamop.weBankAMOP.common.server;

import com.jic.weamop.weBankAMOP.callback.*;
import com.jic.weamop.weBankAMOP.common.config.Config;
import com.jic.weamop.weBankAMOP.common.constants.BlockKeys;
import lombok.Data;
import org.bcos.channel.client.ChannelPushCallback;
import org.bcos.channel.client.Service;
import org.bcos.channel.handler.ChannelConnections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 合约服务类
 *
 * @author v_wbgyang
 */
@Data
@Component
@Lazy(false)
public class ContractServer {
    private static final Logger logger = LoggerFactory.getLogger(ContractServer.class);

    static Service service = new Service();

    static Config config;

    private static String listenTopic;

    private static String connectionsStr;

    @Autowired
    private PushCallback13 pushCallback13;

    @Value("${listen.topic}")
    private void setListenTopic(String listenTopic){
        this.listenTopic = listenTopic;
    }

    @Value("${connectionsStr}")
    private void setConnectionsStr(String connectionsStr){
        this.connectionsStr = connectionsStr;
    }

    public static BigInteger gasPrice = new BigInteger("99999999999");
    public static BigInteger gasLimited = new BigInteger("999999999999999999999");
    public static BigInteger initialValue = new BigInteger("0");
    private String topic = "WEBANK_BCCES_CLS_FEC99782EB3861A194549F95A90580C6";

    ContractServer() {

    }

    // loadConfig 加载配置类
    void loadConfig() {
        //加载配置
        try {
            //这一块配置改动比较少，不写入配置文件配置了，链生成以后一般不用改。
            service.setOrgID("WB");
            service.setConnectSeconds(10);
            service.setConnectSleepPerMillis(10);
            // 设置topic，支持多个topic
            String[] topics = topic.split(",");
            List<String> topicList = new ArrayList<String>();
            for (String s : topics) {
                topicList.add(s);
            }
            service.setTopics(topicList);
            PushCallback pushCallback = new PushCallback();
            service.setPushCallback(pushCallback);

            ConcurrentHashMap<String, ChannelConnections> keyID2connections = new ConcurrentHashMap<>();
            ChannelConnections channelConnections = new ChannelConnections();
            channelConnections.setCaCertPath("classpath:ca.crt");
            channelConnections.setClientKeystorePath("classpath:client.keystore");
            channelConnections.setKeystorePassWord("123456");
            channelConnections.setClientCertPassWord("123456");
            List<String> connectionsStrList = new ArrayList<>();
            String[] split = connectionsStr.split(",");
            for (String s : split) {
                connectionsStrList.add(s);
            }
            channelConnections.setConnectionsStr(connectionsStrList);
            keyID2connections.put("WB",channelConnections);
            service.setAllChannelConnections(keyID2connections);

            //update By taozhouchuan at 2020-11-18 14:03:30 这里，微众的陈老师说可以去掉；
//            setCallBack();
            //启动服务
            logger.info("begin  run service");
            service.run();
            logger.info("service is running");
        } catch (Exception e) {
            logger.info(BlockKeys.BLOCK_ERROR + " start error");
            throw new RuntimeException("service can't start", e);
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
    }

    //AMOP通讯时设置
    private void setCallBack() {

        PushCallback pushCallback = new PushCallback();
        Map<String, TranscationCallBack> callBackMap = new HashMap<String, TranscationCallBack>();
        MyCallback1 myCallback1 = new MyCallback1();
        MyCallback2 myCallback2 = new MyCallback2();
        callBackMap.put("webank1", myCallback1);
        callBackMap.put("nodefront", myCallback2);
        pushCallback.setCallBackMap(callBackMap);

        // 处理消息的PushCallback类，参见Callback代码
        ChannelPushCallback callback = pushCallback;
        try {
            String topic = "WEBANK_BCCES_CLS_FEC99782EB3861A194549F95A90580C6";
            // 设置topic，支持多个topic
            String[] split = topic.split(",");
            List<String> topics = new ArrayList<String>();
            for (String s : split) {
                topics.add(s);
            }
            service.setTopics(topics);
            service.setPushCallback(callback);
        } catch (BeansException e) {
            return;
        }
    }

}
